package com.tbit.uqbike.service.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.constant.RedisConstant;
import com.tbit.uqbike.webmanager.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * rabbitmq监听队列
 * @author <a href="mailto:liu.haoxiang@tbit.com.cn">BUGXiang</a>
 * @version 1.0
 * @since 2024/3/26
 */
@Component
@Slf4j
public class MqMonitor {

    @Resource
    private RedisUtil redisUtil;


    /**
     * 自定义语音监听车辆升级详情
     */
    @RabbitListener(queues = {"${mq.queue.tbitUqbikeVoice}"}, concurrency = "5")
    public void voiceListener(Message message){
        try {
            String respMsg = new String(message.getBody(), StandardCharsets.UTF_8);
            log.info(respMsg);
            /*判断消息类型*/
            JSONObject object = JSON.parseObject(respMsg);
            int msgId = object.getIntValue("msgId");
            /*获取当前最新配置文件版本号*/
            String configVersion = redisUtil.get(RedisConstant.VOICE_CONFIG_KEY);
            if (Objects.isNull(configVersion)){
                log.error("当前缓存版本号为空，本条消息抛弃,消息内容:{}",JSON.toJSONString(respMsg));
            }
            /*消息id为升级任务结果id 并且 版本号一致 lPush到redis*/
            if (40017 == msgId){
                redisUtil.lLeftPush(RedisConstant.VOICE_LPUSH_KEY,respMsg);
            }
        }catch (Exception e){
            log.error("自定义语音解析异常:{}",e.getMessage(),e);
        }
    }

}
